import React from 'react';
import { Card, List, Space, Button, Input, Select, Pagination, Checkbox, Upload } from 'antd';
import { SyncOutlined, UploadOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import UploadUtil from '@/components/UploadUtil';
import { GetFileExt } from '@/services/crud';

const currControl = "Attachment";
const { Search } = Input;
class ViewPage extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            dataSource: [],
            visible: false,
            pageIndex: 1,
            pageSize: 8,
            totalCount: 0,
            payload: {},
            record: {},
            keywords: '',
            fileExt: [],
            ext: null,
            selectId: [],
            gutter: 16,
            column: 4
        }
    }
    componentDidMount() {
        let _this = this;
        this.fetchFileExt();
        if (this.props.gutter) {
            const { gutter, column } = this.props;
            this.setState({ gutter, column, pageSize: column * 2 }, function () {
                _this.fetchDatas();
            })
        } else {
            this.fetchDatas();
        }
    }
    fetchFileExt = async () => {
        const resp = await GetFileExt();
        this.setState({ fileExt: resp?.result });
    }
    fetchDatas = () => {
        this.setState({ loading: true });
        const { pageIndex, pageSize, keywords, ext } = this.state;
        this.props.dispatch({
            type: "Abp/getList",
            payload: { SkipCount: (pageIndex - 1) * pageSize, MaxResultCount: pageSize, keywords, ext },
            control: currControl
        }).then(() => {
            var resp = this.props.response;
            if (resp && resp.result) {
                var dataSource = resp.result.items;
                this.setState({ loading: false, dataSource, totalCount: resp.result.totalCount });
            }
        });
    }
    onSearch = (keywords: any) => {
        this.setState({ keywords }, () => {
            this.fetchDatas();
        });
    }
    onPageChange = (page: any, pageSize: any = 12) => {
        let _this = this;
        this.setState({
            pageIndex: page,
            pageSize
        }, function () {
            _this.fetchDatas();
        });
    };
    signleSelect = (val: any) => {
        if (this.props.clickFun) {
            this.props.clickFun(val);
        }
    }
    multiSelect = (e: any, item: any) => {
        const { selectId } = this.state;
        let Ids: string[] = selectId;
        if (e.target.checked) {
            if (!Ids.includes(item.sysRowID)) {
                Ids.push(item.sysRowID);
                this.setState({ selectId: Ids });
            }
        }
        else {
            if (Ids.includes(item.sysRowID)) {
                var index = Ids.indexOf(item.sysRowID);
                if (index > -1) {
                    Ids.splice(index, item.sysRowID.length);
                }
                this.setState({ selectId: Ids });
            }
        }
        console.log(Ids);

    }
    doMultiSelect = () => {
        if (this.props.clickMultiFun) {
            const { selectId } = this.state;
            this.props.clickMultiFun(selectId);
        }
    }
    handleUpload = (info: any) => {
        this.fetchDatas();
    }
    doDelete = (info: any) => {
        const { selectId, dataSource } = this.state;
        var arr = dataSource.filter((o: any) => selectId.includes(o.sysRowID));
        arr.forEach((item: any) => {
            this.props.dispatch({
                type: "Abp/delete",
                payload: { id: item.id },
                control: currControl
            })
        });
        this.fetchDatas()
    }
    doRefresh = () => {
        let _this = this;
        this.setState({ ext: null }, function () {
            _this.fetchDatas();
        })
    }
    render() {
        const { loading, dataSource, pageIndex, totalCount, pageSize, selectId, fileExt, gutter, column } = this.state;
        const firstPZ = column * 2
        return (
            <div>
                <Card>
                    <Space>
                        <Button type="primary"
                            onClick={this.doRefresh}
                            loading={loading}
                            icon={<SyncOutlined />} >刷新</Button>
                        <Select style={{ width: 100 }} placeholder="文件格式" onChange={value => this.setState({ ext: value })}>
                            {
                                fileExt ? fileExt.map((item: any) => {
                                    return (
                                        <Select.Option
                                            key={item}
                                            value={item}>{item}
                                        </Select.Option>
                                    )
                                }) : null
                            }
                        </Select>
                        <Search style={{ width: 160 }} placeholder="输入关键词搜索" onSearch={value => this.onSearch(value)} />
                        <Upload
                            action={UploadUtil.actionURL}
                            headers={{
                                'Authorization': UploadUtil.accessToken,
                            }}
                            showUploadList={false}
                            multiple={true}
                            onChange={this.handleUpload}>
                            <Button icon={<UploadOutlined />}>上传</Button>
                        </Upload>
                        <Button danger onClick={this.doDelete} >删除</Button>
                        <Button type="primary"
                            onClick={this.doMultiSelect} >已选择 {selectId.length} 个</Button>
                    </Space>
                </Card>
                <Card style={{borderTop:0}}>
                    <List
                        grid={{ gutter, column }}
                        dataSource={dataSource}
                        renderItem={(item: any) => (
                            <List.Item>
                                <Card cover={<img alt={item.fileName} src={UploadUtil.imgServ + item.sysRowID} onClick={() => this.signleSelect(item.sysRowID)} />} >
                                    <Checkbox onChange={(e: any) => this.multiSelect(e, item)} /> {item.fileName}</Card>
                            </List.Item>
                        )}
                    />

                    <Pagination
                        defaultCurrent={pageIndex}
                        pageSize={pageSize}
                        total={totalCount}
                        onChange={this.onPageChange}
                        pageSizeOptions={[firstPZ.toString(), (firstPZ * 2).toString(), (firstPZ * 3).toString(), (firstPZ * 5).toString()]}
                        showTotal={total => `共 ${total} 条`} />
                </Card>
            </div>
        )
    }
}
export default connect(({ Abp }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
}))(ViewPage);